package com.example.b_308.myapplication.service.base;

/**
 * Created by tongkang on 2017/6/9.
 */


import android.content.Context;

import com.example.b_308.myapplication.comment.base.MultiListeners;

/**
 * 服务的抽象类
 */
public abstract class BaseService extends MultiListeners implements IBaseService {
    /**
     * 上下文
     */
    private Context context;
    /**
     * 服务状态
     */
    private ServiceStatus serviceStatus;

    /**
     * 构造方法
     */
    public BaseService() {
    }

    /**
     * 服务开始
     *
     * @param context
     * @throws Exception
     */
    public void start(Context context) throws Exception {
        //当状态在运行的时候，抛出一个正在运行的异常
        if (this.serviceStatus == ServiceStatus.Running) {
            throw new IllegalStateException("Service already running.");
        } else {
            //不在运行的时候，启动服务
            this.context = context;
            this.onStart();
            this.serviceStatus = ServiceStatus.Running;
        }
    }

    /**
     * 服务停止
     *
     * @throws Exception
     */
    public void stop() throws Exception {
        //当服务已经停跑出异常
        if (this.serviceStatus == ServiceStatus.Stopped) {
            throw new IllegalStateException("Service already stopped.");
        } else {
            //否则停止服务，将状态改为停止
            this.onStop();
            this.serviceStatus = ServiceStatus.Stopped;
        }
    }

    /**
     * 开始的抽象方法
     *
     * @throws Exception
     */
    protected abstract void onStart() throws Exception;
    /**
     * 结束的抽象方法
     *
     * @throws Exception
     */
    protected abstract void onStop() throws Exception;
    /**
     * 获取服务状态
     *
     * @return ServiceStatus
     */
    public ServiceStatus getServiceStatus() {
        return this.serviceStatus;
    }

    /**
     * 获取上下文
     *
     * @return Context
     */
    public Context getContext() {
        return this.context;
    }
}
